<?php

namespace core\libs;

/*
 * 处理Excel导出 (以下为示例)  
	 * $datas = array(
			"title" => array('列表1', '列表2'),
			"lists" => array(
				array('111', '222'),
				array('aaa', 'ccc')
			)
	 * );
     * $excel = new \core\libs\excel($datas, '测试');
	 * $excel->export(); 
 */
class excel {	
    private $datas = [];
    private $filename = "";
	//构造方法
	public function __construct($datas = array(), $filename = "data") {
        $this->datas = $datas;
        $this->filename = $filename;
	}  
	
	/* 
	*处理Excel导出 
	*@param $filename string 表前缀
	*@param $datas array     设置表格数据 
	*/ 
	public function export() {
        // 输出Excel文件头
		header('Content-Type: application/vnd.ms-excel');
		header("Content-Disposition: attachment;filename = {$this->filename}-". date('YmdHis', time()) .".csv");
		header('Cache-Control: max-age=0');
 
		// 打开PHP文件句柄，php://output 表示直接输出到浏览器
		$fp = fopen('php://output', 'a');
 
		// 输出Excel列名信息
		foreach ($this->datas["title"] as $i => $val) {
			$head[$i] = iconv('utf-8', 'gbk', $val);
		}
		// 将数据通过fputcsv写到文件句柄
		fputcsv($fp, $head);
 
		// 输出Excel内容
		foreach ($this->datas["lists"] as $arr) {
			$row = array();
			foreach ($arr as $j => $v) {
				$row[$j] = iconv('utf-8', 'gbk', $v);
			}
			fputcsv($fp, $row);
        }
	}
}

?>